package com.ddone.mode.worker;

import com.ddone.util.RabbitMqConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author ddone
 * @date 2024/4/4-19:07
 *
 * Work 模型
 *  多个消费者 消费 同一个队列中的消息, 每个消息只能消费一次
 *  作用: 避免消息积压
 * 问题:
 *  消息避免丢失
 *      生产者发送消息导致丢失
 *      mq宕机导致消息丢失
 *      消费者消费消息导致丢失: 手动ack
 *  消息积压
 *      多个消费者消费同一个队列消息
 *
 */
public class WorkConsumer1 {
    private final static String QUEUE_NAME = "work_queue";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitMqConnectionUtil.getConnection();

        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 配置能者多劳, 指定有一次获取几条信息, 消息消费成功 ack之后,mq才能分发下一条消息
        channel.basicQos(1);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body);
                System.out.println("[消费者1] consume : " + msg + "!");

                // 模拟消耗时间
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }
}
